package com.dxysun.design.proxy.jdkproxy;

import com.dxysun.design.proxy.ISubject;
import com.dxysun.design.proxy.RealSubject;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxy implements InvocationHandler
{
	private ISubject target;

	public ISubject getInstance(ISubject target)
	{
		this.target = target;
		Class<?> clazz = target.getClass();
		return (ISubject) Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
	{
		before();
		Object res = method.invoke(target, args);
		after();
		return res;
	}

	private void after()
	{
		System.out.println("jdk call service after");

	}

	private void before()
	{
		System.out.println("jdk call service before");
	}

	public static void main(String[] args)
	{
		JdkProxy jdkProxy = new JdkProxy();
		ISubject subject = jdkProxy.getInstance(new RealSubject());
		subject.request();
	}
}
